class ElectionsController < ApplicationController

  hobo_model_controller
  
  # Creates a new election, receiving voter and candidate lists
  def create
    
    # Create election from parameters and check permissions
    @election = Election.new(params[:election])
    @election.owner = current_user
    
    # Validates existence of candidates
    if params[:candidate].nil?
      flash[:notice] = "Please insert at least one candidate"
      redirect_back_or_default(:action => 'new')
      return
    end
    # Check and add each candidate
    candidates = Array.new    
    params[:candidate].each do |c|
      candidate = Candidate.new(c[1])
      candidate.election = @election
      candidates << candidate      
    end
    
    # Validates existence of voters
    if params[:voters].nil?
      flash[:notice] = "Please insert at least one voter"
      redirect_back_or_default(:action => 'new')
      return
    end
    
    # Check and add voters lists
    voter_emails = params[:voters]
    voter_emails = voter_emails.split(/(,|\s)+/).uniq.compact
    voter_emails.delete_if { |a| !a.match(/\s+/).nil? }
    voter_emails.delete_if { |a| a.match(/\w/).nil? }    
    voters = Array.new
    voter_emails.each do |email|
      voters << User.find_or_create(email)
    end
    
    # Create voting ballots
    ballots = Array.new    
    voters.each do |voter|
      ballot = Ballot.new_from_params(voter, @election)
      ballots << ballot
    end
    
    # Save the records to the database
    begin
      Election.transaction do
        @election.save!        
        candidates.each {|c| c.save! }
        ballots.each {|b| b.save!}
      end
    rescue Exception
      render :action => :new and return
    end
    
    # If everything went ok, notify the voters
    for voter in voters
      Notifier.deliver_election_warning(voter,@election)
    end
    flash[:notice] = "Election created successfully"
    redirect_to(object_url(@election))
  end

end
